<template>
  <div>
    <img
      src="./teable.png"
      alt=""
      v-if="isDev"
      style="width: 100%; height: auto"
    />
    <iframe
      v-else-if="tableid && viewid && !isDev"
      :src="loadUrl"
      style="
        width: 100vw;
        height: 100vh;
        border: none;
        outline: 0;
        overflow: hidden;
      "
      :style="isDev ? 'pointer-events: none;' : ''"
      title="Multidimensional Table"
      ref="teable_iframe"
    ></iframe>
  </div>
</template>

<script>
import useMappingProps from 't/common/hooks/useMappingProps';
import { createNameSpace } from 't/common/utils';
import { ref, defineComponent, watch, computed, onMounted } from 'vue';
import styles from './index.module.scss';
import './index.scss';
import CDOProxy from './CDOProxy.ts';
import { is } from 't';
export default defineComponent({
  name: createNameSpace('multidimensional-table'),
  props: [
    'viewid',
    'tableid',
    'isDev',
    'isEditField',
    'cDO',
    'useCDO',
    'fieldMapping',
    'selectDataSource',
  ],
  components: {},
  setup(props, { attrs, emit, expose, slots }) {
    const [mappingProps, mappingExpose] = useMappingProps(props);
    expose(mappingExpose);
    const teable_iframe = ref(null);
    const iframeLoadId = Funcs.Guid();
    onMounted(async () => {
      if (mappingProps.useCDO && mappingProps.cDO) {
        const cdoProxy = new CDOProxy(
          mappingProps.cDO,
          mappingProps.fieldMapping,
          teable_iframe.value?.contentWindow,
        );
        let promiseList = [];
        let  handleUpdateOptions = null
        if (mappingProps.selectDataSource) {
          // cdoProxy.setSelectDataSource(mappingProps.selectDataSource);
          /**
           * 处理数据源
           */
          let selestDataSource = await mappingProps.selectDataSource();

          if (selestDataSource) {
            for (let i in selestDataSource) {
              if (
                selestDataSource[i].dataList &&
                typeof selestDataSource[i].dataList === 'function'
              ) {
                // new Promise((resolve, reject) => {
                //   let data = selestDataSource[i].dataList();
                //   data.then(res => {
                //     selestDataSource[i].dataList = res.List;
                //   });
                // });

                promiseList.push(
                  new Promise((resolve, reject) => {
                    let data = selestDataSource[i].dataList();
                    data
                      .then(res => {
                        selestDataSource[i].dataList = res.List;
                        resolve();
                      })
                      .catch(err => {
                        delete selestDataSource[i];
                        console.error('获取数据源失败', err);
                        resolve(err);
                      });
                  }),
                );

                if (promiseList.length > 0) {

                  // 只执行一次 updateoptions 相关逻辑
                  let updateOptionsHandled = false;
                  handleUpdateOptions = (event) => {
                    if (
                      event.data &&
                      event.data.type === 'updateoptions' &&
                      !updateOptionsHandled
                    ) {
                      updateOptionsHandled = true;
                      // 这里写需要在收到 updateoptions 后执行的逻辑
                      // ...
                      Promise.all(promiseList).then(() => {
                        // 等待 iframe 加载完成后再通知
                        setTimeout(() => {
                          teable_iframe.value?.contentWindow.postMessage(
                            {
                              type: 'updateoptions',
                              payload: selestDataSource,
                            },
                            '*',
                          );
                        }, 0);
                      });


                    }

                  };

                }
              }
            }
          }
        }
        // 监听 postMessage 抛出来的信息，key 为 cdo_iframeLoadId
        window.addEventListener('message', event => {
          console.log('接收到 postMessage 信息', event.data);
          if (event.data && event.data.key === `cdo_${iframeLoadId}`) {
            switch (event.data.payload.type) {
              case 'create':
                // 初始化 CDO
                cdoProxy.create(event.data.payload.data);
                break;
              case 'update':
                // 初始化 CDO
                cdoProxy.update(event.data.payload.data);
                break;
              case 'delete':
                // 初始化 CDO
                cdoProxy.delete(event.data.payload.data);
                break;
            }
          }else if (event.data && event.data.type === 'updateoptions') {
            // 处理 updateoptions
            console.log('接收到 updateoptions', event.data.payload);
            if (handleUpdateOptions) {
              handleUpdateOptions(event);
            }
           }

        });
      }
    });

    const label = ref('');
    const isDev = ref(false);
    if (isDev.value && !mappingProps.tableid) {
      mappingProps.tableid = 'tbl2uxpcvCaI2tPJDoO';
      mappingProps.viewid = 'viwttBSbCzqPapy1775';
    }
    const loadUrl = computed(() => {
      // if (!window.location.hostname == 'fastest.teld8.xyz' || isDev.value) {
      //   return `http://localhost:12200/fasteable/base/public/${mappingProps.tableid || 'tbl2uxpcvCaI2tPJDoO'}/${mappingProps.viewid || 'viwttBSbCzqPapy1775'}?userName=${window.Session?.Alias || window.Session?.UserName || 'Teld'}&userId=${window.Session?.UserId || 'Teld'}`;
      // }
      let pas = `&isEditField=${mappingProps.isEditField || false}${mappingProps.useCDO && mappingProps.cDO ? '&iframeLoadId=' + iframeLoadId : ''}`;
      return `${window.location.protocol}//${ window.location.hostname || 'localhost'}:12200/fasteable/base/public/${mappingProps.tableid || 'tbl2uxpcvCaI2tPJDoO'}/${mappingProps.viewid || 'viwttBSbCzqPapy1775'}?userName=${window.Session?.Alias || window.Session?.UserName || 'Teld'}&userId=${window.Session?.UserId || 'Teld'}${isDev.value ? '' : pas}`;
    });
    if (!mappingProps.isDev) {
      //  window.location.replace(loadUrl.value);
    } else {
      isDev.value = true;
    }

    return {
      isDev,
      label,
      loadUrl,
      tableid: mappingProps.tableid,
      viewid: mappingProps.viewid,
      teable_iframe,
    };
  },
});
</script>
